import type { App } from 'vue'

// 插件选项接口
interface CustomPluginOptions {
  prefix?: string
  globalMessage?: string
}

// 全局属性接口 - 用于类型提示
declare module 'vue' {
  interface ComponentCustomProperties {
    $customMessage: (msg: string) => void
    $formatText: (text: string) => string
    $showCustomModal: (title: string, content: string) => void
    $simpleMessage: () => void
    $getConfig: <K extends string>(key: K) => any
  }
}

// 第一种方式：对象形式的插件（推荐）
export const CustomPlugin = {
  install(app: App, options: CustomPluginOptions = {}) {
    const { prefix = '[Plugin]', globalMessage = 'Hello from Custom Plugin!' } = options
    
    console.log('🚀 CustomPlugin 正在安装...')
    
    // 1. 添加全局属性和方法
    app.config.globalProperties.$customMessage = (msg: string) => {
      console.log(`${prefix} ${msg}`)
      alert(`${prefix} ${msg}`)
    }
    
    app.config.globalProperties.$formatText = (text: string) => {
      return `${prefix} ${text} - ${new Date().toLocaleTimeString()}`
    }
    
    // 2. 添加全局组件
    app.component('CustomAlert', {
      props: {
        message: {
          type: String,
          default: globalMessage
        },
        type: {
          type: String,
          default: 'info'
        }
      },
      template: `
        <div :class="['custom-alert', 'custom-alert--' + type]">
          <span class="custom-alert__icon">{{ getIcon() }}</span>
          <span class="custom-alert__message">{{ message }}</span>
        </div>
      `,
      methods: {
        getIcon(): string {
          const icons: Record<string, string> = {
            info: 'ℹ️',
            success: '✅',
            warning: '⚠️',
            error: '❌'
          }
          const type = (this as any).type as string
          return icons[type] || '📢'
        }
      }
    })
    
    // 3. 添加全局指令
    app.directive('highlight', {
      mounted(el: HTMLElement, binding) {
        el.style.backgroundColor = binding.value || 'yellow'
        el.style.padding = '4px'
        el.style.borderRadius = '4px'
        el.style.transition = 'all 0.3s ease'
      },
      updated(el: HTMLElement, binding) {
        el.style.backgroundColor = binding.value || 'yellow'
      }
    })
    
    // 4. 提供全局数据 (Vue 3的provide/inject)
    app.provide('customPluginConfig', {
      prefix,
      globalMessage,
      version: '1.0.0'
    })
    
    // 5. 添加实例方法
    app.config.globalProperties.$showCustomModal = (title: string, content: string) => {
      const modalHtml = `
        <div id="custom-modal" style="
          position: fixed;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          background-color: rgba(0,0,0,0.5);
          display: flex;
          justify-content: center;
          align-items: center;
          z-index: 9999;
        ">
          <div style="
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            max-width: 400px;
            width: 90%;
          ">
            <h3 style="margin: 0 0 10px 0; color: #333;">${title}</h3>
            <p style="margin: 0 0 20px 0; color: #666;">${content}</p>
            <button onclick="document.getElementById('custom-modal').remove()" style="
              background: #007bff;
              color: white;
              border: none;
              padding: 8px 16px;
              border-radius: 4px;
              cursor: pointer;
            ">关闭</button>
          </div>
        </div>
      `
      document.body.insertAdjacentHTML('beforeend', modalHtml)
    }
    
    // 6. 插件初始化完成回调
    console.log('✅ CustomPlugin 安装完成!')
    console.log('可用的全局方法：')
    console.log('- this.$customMessage(message)')
    console.log('- this.$formatText(text)')
    console.log('- this.$showCustomModal(title, content)')
    console.log('- <CustomAlert message="..." type="..." />')
    console.log('- v-highlight="color"')
  }
}

// 第二种方式：函数形式的插件
export function createSimplePlugin(defaultMessage: string = '简单插件消息') {
  return (app: App) => {
    console.log('📦 SimplePlugin 正在安装...')
    
    app.config.globalProperties.$simpleMessage = () => {
      console.log(defaultMessage)
    }
    
    console.log('✅ SimplePlugin 安装完成!')
  }
}

// 第三种方式：带类型安全的插件工厂
export function createTypedPlugin<T extends Record<string, any>>(config: T) {
  return {
    install(app: App) {
      console.log('🔧 TypedPlugin 正在安装...')
      
      // 将配置注入到全局
      app.provide('typedPluginConfig', config)
      
      // 添加类型化的全局方法
      app.config.globalProperties.$getConfig = <K extends keyof T>(key: K): T[K] => {
        return config[key]
      }
      
      console.log('✅ TypedPlugin 安装完成!')
    }
  }
}

export default CustomPlugin